package com.fanfou.api
{
	import com.fanfou.utils.FanfouConfig;
	import com.utils.StringEncoders;
	import com.fanfou.utils.URLUtil;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	public class FileUpload extends AbstractAPI_FF
	{
		public function FileUpload()
		{
		}
		
		public static var imageRe:RegExp = /http:\/\/\S+\.(?:jpg|png|gif)/;
		private static const CONTENT_TYPE_JPEG:String="Content-Type: image/pjpeg";
		private static const MULTIPART_FORMDATA:String="multipart/form-data; boundary=";
		private static const CONTENT_DISPOSITION_BASIC:String='Content-Disposition: form-data; name="$name"';
		
		public function uploadPhoto(photoData:Object,text:String):void{
			var imgData:ByteArray = photoData as ByteArray;
			imgData.position = 0;
			var url:String = config.baseURL + URLUtil.UPLOAD_PHOTO;
			url = url + '.' + config.dataFormat;
			var variables:URLVariables = new URLVariables();
			var urlRequest:URLRequest = signRequest(URLRequestMethod.POST,url, variables, true);
			var boundary:String=makeBoundary();
			urlRequest.contentType = MULTIPART_FORMDATA + boundary;
			urlRequest.data['status'] = text;
			urlRequest.data = makeMultipartPostData(boundary, "photo", imgData, urlRequest.data);
			urlLoader = new URLLoader;
			_addEventListener();
			urlLoader.load(urlRequest);
		}
		
		private function makeMultipartPostData(boundary:String, imgFieldName:String, imgData:ByteArray, params:Object):Object
		{
			var req:URLRequest=new URLRequest();
			var postData:ByteArray=new ByteArray();
			postData.endian=Endian.BIG_ENDIAN;
			var value:String;
			//add params to the post data.
			if (params)
			{
				for (var name:String in params)
				{
					boundaryPostData(postData, boundary);
					addLineBreak(postData);
					//writeStringToByteArray(postData, CONTENT_DISPOSITION_BASIC.replace("$name", name));
					postData.writeUTFBytes(CONTENT_DISPOSITION_BASIC.replace("$name", name));
					addLineBreak(postData);
					addLineBreak(postData);
					postData.writeUTFBytes(params[name]);
					addLineBreak(postData);
				}
			}
			boundaryPostData(postData, boundary);
			addLineBreak(postData);
			//writeStringToByteArray(postData, CONTENT_DISPOSITION_BASIC.replace("$name", "files") + '; filename="'+filename + '"');
			postData.writeUTFBytes(CONTENT_DISPOSITION_BASIC.replace("$name", imgFieldName) + '; filename=temp');
			addLineBreak(postData);
			//writeStringToByteArray(postData, CONTENT_TYPE_JPEG);
			postData.writeUTFBytes(CONTENT_TYPE_JPEG);
			addLineBreak(postData);
			//writeStringToByteArray(postData,CONTENT_TRANSFER_ENCODING);
			//postData.writeUTFBytes(CONTENT_TRANSFER_ENCODING);
			//addLineBreak(postData);
			addLineBreak(postData);
			postData.writeBytes(imgData, 0, imgData.length);
			addLineBreak(postData);
			
			boundaryPostData(postData, boundary);
			addDoubleDash(postData);
			
			postData.position=0;
			return postData;
		}
		
		private function boundaryPostData(data:ByteArray, boundary:String):void
		{
			var len:int=boundary.length;
			addDoubleDash(data);
			for (var i:int=0; i < len; ++i)
			{
				data.writeByte(boundary.charCodeAt(i));
			}
		}
		
		private function addDoubleDash(data:ByteArray):void
		{
			data.writeShort(0x2d2d);
		}
		
		private function addLineBreak(data:ByteArray):void
		{
			data.writeShort(0x0d0a);
		}
		
		private function makeBoundary():String
		{
			var boundary:String="";
			for (var i:int=0; i < 13; i++)
			{
				boundary+=String.fromCharCode(int(97 + Math.random() * 25));
			}
			boundary="---------------------------" + boundary;
			return boundary;
		}
		
		private function encodeMsg(status:String):String
		{
			var source:String = status;
			var pattern1:RegExp = new RegExp('^[ ]+|[ ]+$', 'g');
			source = source.replace(pattern1, '');		
			var pattern2:RegExp = new RegExp('[ \n\t\r]', 'g');
			source = source.replace(pattern2, ' ');				
			var pattern3:RegExp = /( )+/g;
			source = source.replace(pattern3, ' ');			
			return StringEncoders.urlEncodeSpecial(source);
		}
		
		override protected function completeHandler(event:Event):void{
			dispatchEvent(event.clone());
			_removeEventListener();
		}
		override protected function errorHandler(event:IOErrorEvent):void{
			dispatchEvent(event.clone());
			_removeEventListener();
		}
	}
}